<template>
  <div class="refund-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="退款单号">
          <el-input
            v-model="searchForm.refundNumber"
            placeholder="请输入退款单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="原订单号">
          <el-input
            v-model="searchForm.orderNumber"
            placeholder="请输入原订单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="退款状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择退款状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" value="pending" />
            <el-option label="审核通过" value="approved" />
            <el-option label="审核拒绝" value="rejected" />
            <el-option label="退款中" value="processing" />
            <el-option label="退款成功" value="success" />
            <el-option label="退款失败" value="failed" />
          </el-select>
        </el-form-item>

        <el-form-item label="退款原因">
          <el-select
            v-model="searchForm.reason"
            placeholder="选择退款原因"
            clearable
            style="width: 150px"
          >
            <el-option label="用户申请" value="user_request" />
            <el-option label="活动取消" value="event_cancelled" />
            <el-option label="系统错误" value="system_error" />
            <el-option label="重复支付" value="duplicate_payment" />
            <el-option label="其他原因" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="申请时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-bar">
        <div class="action-left">
          <el-button
            type="success"
            :disabled="!selectedRefunds.length"
            @click="handleBatchApprove"
          >
            <IconifyIconOffline icon="ep:check" class="mr-1" />
            批量通过
          </el-button>
          <el-button
            type="danger"
            :disabled="!selectedRefunds.length"
            @click="handleBatchReject"
          >
            <IconifyIconOffline icon="ep:close" class="mr-1" />
            批量拒绝
          </el-button>
          <el-button type="primary" @click="handleExport">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出数据
          </el-button>
        </div>

        <div class="action-right">
          <el-button type="info" @click="handleStatistics">
            <IconifyIconOffline icon="ep:data-analysis" class="mr-1" />
            退款统计
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 退款列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="refundList"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column
          prop="refundNumber"
          label="退款单号"
          width="180"
          fixed="left"
        >
          <template #default="{ row }">
            <el-link type="primary" @click="handleViewDetail(row)">
              {{ row.refundNumber }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column prop="orderNumber" label="原订单号" width="180">
          <template #default="{ row }">
            <el-link type="info" @click="handleViewOrder(row)">
              {{ row.orderNumber }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="用户信息" width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.user.avatar">
                <IconifyIconOffline icon="ep:user" />
              </el-avatar>
              <div class="user-detail">
                <div class="username">{{ row.user.username }}</div>
                <div class="phone">{{ row.user.phone }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          prop="productName"
          label="商品名称"
          width="200"
          show-overflow-tooltip
        />

        <el-table-column label="金额信息" width="150">
          <template #default="{ row }">
            <div class="amount-info">
              <div class="original-amount">
                原价：¥{{ row.originalAmount.toFixed(2) }}
              </div>
              <div class="refund-amount">
                退款：¥{{ row.refundAmount.toFixed(2) }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="reason" label="退款原因" width="120">
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ getReasonText(row.reason) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="退款状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="applyTime" label="申请时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.applyTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="processTime" label="处理时间" width="160">
          <template #default="{ row }">
            {{ row.processTime ? formatDateTime(row.processTime) : "-" }}
          </template>
        </el-table-column>

        <el-table-column prop="processor" label="处理人" width="100">
          <template #default="{ row }">
            {{ row.processor || "-" }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row)"
            >
              查看
            </el-button>

            <el-button
              v-if="row.status === 'pending'"
              type="success"
              size="small"
              @click="handleApprove(row)"
            >
              通过
            </el-button>

            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              size="small"
              @click="handleReject(row)"
            >
              拒绝
            </el-button>

            <el-button
              v-if="row.status === 'approved'"
              type="warning"
              size="small"
              @click="handleProcess(row)"
            >
              处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 退款详情弹窗 -->
    <el-dialog v-model="detailVisible" title="退款详情" width="800px">
      <div v-if="currentRefund" class="refund-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退款单号" :span="2">
            <el-text type="primary" size="large" tag="b">
              {{ currentRefund.refundNumber }}
            </el-text>
          </el-descriptions-item>

          <el-descriptions-item label="原订单号">
            <el-link type="info" @click="handleViewOrder(currentRefund)">
              {{ currentRefund.orderNumber }}
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="退款状态">
            <el-tag :type="getStatusColor(currentRefund.status)">
              {{ getStatusText(currentRefund.status) }}
            </el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="用户名">
            {{ currentRefund.user.username }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentRefund.user.phone }}
          </el-descriptions-item>

          <el-descriptions-item label="商品名称" :span="2">
            {{ currentRefund.productName }}
          </el-descriptions-item>

          <el-descriptions-item label="原订单金额">
            <el-text type="danger" tag="b">
              ¥{{ currentRefund.originalAmount.toFixed(2) }}
            </el-text>
          </el-descriptions-item>
          <el-descriptions-item label="退款金额">
            <el-text type="danger" tag="b">
              ¥{{ currentRefund.refundAmount.toFixed(2) }}
            </el-text>
          </el-descriptions-item>

          <el-descriptions-item label="退款原因">
            {{ getReasonText(currentRefund.reason) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatDateTime(currentRefund.applyTime) }}
          </el-descriptions-item>

          <el-descriptions-item label="处理时间">
            {{
              currentRefund.processTime
                ? formatDateTime(currentRefund.processTime)
                : "-"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="处理人">
            {{ currentRefund.processor || "-" }}
          </el-descriptions-item>

          <el-descriptions-item label="退款说明" :span="2">
            {{ currentRefund.remark || "-" }}
          </el-descriptions-item>

          <el-descriptions-item
            v-if="currentRefund.processRemark"
            label="处理备注"
            :span="2"
          >
            {{ currentRefund.processRemark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button
          v-if="currentRefund?.status === 'pending'"
          type="success"
          @click="handleApprove(currentRefund)"
        >
          通过
        </el-button>
        <el-button
          v-if="currentRefund?.status === 'pending'"
          type="danger"
          @click="handleReject(currentRefund)"
        >
          拒绝
        </el-button>
      </template>
    </el-dialog>

    <!-- 处理退款弹窗 -->
    <el-dialog v-model="processVisible" title="处理退款" width="500px">
      <div v-if="currentRefund" class="process-form">
        <el-form :model="processForm" label-width="100px">
          <el-form-item label="退款单号">
            <el-input v-model="currentRefund.refundNumber" disabled />
          </el-form-item>

          <el-form-item label="退款金额">
            <el-input v-model="currentRefund.refundAmount" disabled>
              <template #prepend>¥</template>
            </el-input>
          </el-form-item>

          <el-form-item label="处理结果">
            <el-radio-group v-model="processForm.result">
              <el-radio value="approve">通过退款</el-radio>
              <el-radio value="reject">拒绝退款</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="处理备注">
            <el-input
              v-model="processForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入处理备注"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="processVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitProcess"
          >确认处理</el-button
        >
      </template>
    </el-dialog>

    <!-- 统计弹窗 -->
    <el-dialog v-model="statisticsVisible" title="退款统计" width="800px">
      <div class="statistics-content">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总退款单数" :value="statistics.totalCount" />
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="总退款金额"
              :value="statistics.totalAmount"
              prefix="¥"
              :precision="2"
            />
          </el-col>
          <el-col :span="6">
            <el-statistic title="成功退款" :value="statistics.successCount" />
          </el-col>
          <el-col :span="6">
            <el-statistic
              title="成功率"
              :value="statistics.successRate"
              suffix="%"
              :precision="1"
            />
          </el-col>
        </el-row>

        <div class="chart-container">
          <div ref="chartRef" style="width: 100%; height: 300px" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import * as echarts from "echarts";
import dayjs from "dayjs";

const router = useRouter();

// 状态
const loading = ref(false);
const detailVisible = ref(false);
const processVisible = ref(false);
const statisticsVisible = ref(false);
const selectedRefunds = ref([]);
const currentRefund = ref(null);
const chartRef = ref();

// 搜索表单
const searchForm = reactive({
  refundNumber: "",
  orderNumber: "",
  username: "",
  status: "",
  reason: "",
  dateRange: []
});

// 处理表单
const processForm = reactive({
  result: "approve",
  remark: ""
});

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
});

// 统计数据
const statistics = reactive({
  totalCount: 156,
  totalAmount: 12580.5,
  successCount: 142,
  successRate: 91.0
});

// 退款列表数据
const refundList = ref([
  {
    id: 1,
    refundNumber: "RF202401150001",
    orderNumber: "ORD202401150001",
    user: {
      username: "张三",
      phone: "13800138001",
      avatar:
        "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=male%20user%20avatar&image_size=square"
    },
    productName: "春季篮球赛报名费",
    originalAmount: 50.0,
    refundAmount: 50.0,
    reason: "user_request",
    status: "pending",
    applyTime: "2024-01-15 14:30:00",
    processTime: null,
    processor: null,
    remark: "临时有事无法参加比赛",
    processRemark: null
  },
  {
    id: 2,
    refundNumber: "RF202401140002",
    orderNumber: "ORD202401140008",
    user: {
      username: "李四",
      phone: "13800138002",
      avatar:
        "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=female%20user%20avatar&image_size=square"
    },
    productName: "羽毛球培训课程",
    originalAmount: 200.0,
    refundAmount: 200.0,
    reason: "event_cancelled",
    status: "success",
    applyTime: "2024-01-14 16:20:00",
    processTime: "2024-01-14 17:30:00",
    processor: "管理员",
    remark: "培训课程因故取消",
    processRemark: "活动取消，全额退款"
  }
]);

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm:ss");
};

// 获取退款状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "待审核",
    approved: "审核通过",
    rejected: "审核拒绝",
    processing: "退款中",
    success: "退款成功",
    failed: "退款失败"
  };
  return statusMap[status] || status;
};

// 获取退款状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: "warning",
    approved: "primary",
    rejected: "danger",
    processing: "info",
    success: "success",
    failed: "danger"
  };
  return colorMap[status] || "info";
};

// 获取退款原因文本
const getReasonText = (reason: string) => {
  const reasonMap: Record<string, string> = {
    user_request: "用户申请",
    event_cancelled: "活动取消",
    system_error: "系统错误",
    duplicate_payment: "重复支付",
    other: "其他原因"
  };
  return reasonMap[reason] || reason;
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadRefundList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    refundNumber: "",
    orderNumber: "",
    username: "",
    status: "",
    reason: "",
    dateRange: []
  });
  handleSearch();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRefunds.value = selection;
};

// 查看详情
const handleViewDetail = (row: any) => {
  currentRefund.value = row;
  detailVisible.value = true;
};

// 查看订单
const handleViewOrder = (row: any) => {
  router.push(`/order/detail/${row.orderNumber}`);
};

// 通过退款
const handleApprove = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要通过退款申请 "${row.refundNumber}" 吗？`,
      "确认通过",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }
    );

    row.status = "approved";
    row.processTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    row.processor = "当前用户";

    ElMessage.success("退款申请已通过");
    detailVisible.value = false;
  } catch {
    // 用户取消
  }
};

// 拒绝退款
const handleReject = async (row: any) => {
  try {
    const { value } = await ElMessageBox.prompt(
      `请输入拒绝退款的原因：`,
      "拒绝退款",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "textarea",
        inputPlaceholder: "请输入拒绝原因"
      }
    );

    row.status = "rejected";
    row.processTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    row.processor = "当前用户";
    row.processRemark = value;

    ElMessage.success("退款申请已拒绝");
    detailVisible.value = false;
  } catch {
    // 用户取消
  }
};

// 处理退款
const handleProcess = (row: any) => {
  currentRefund.value = row;
  processForm.result = "approve";
  processForm.remark = "";
  processVisible.value = true;
};

// 提交处理
const handleSubmitProcess = () => {
  if (!processForm.remark) {
    ElMessage.warning("请输入处理备注");
    return;
  }

  if (currentRefund.value) {
    if (processForm.result === "approve") {
      currentRefund.value.status = "processing";
      ElMessage.success("退款处理中");
    } else {
      currentRefund.value.status = "rejected";
      ElMessage.success("退款申请已拒绝");
    }

    currentRefund.value.processTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
    currentRefund.value.processor = "当前用户";
    currentRefund.value.processRemark = processForm.remark;
  }

  processVisible.value = false;
};

// 批量通过
const handleBatchApprove = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量通过选中的 ${selectedRefunds.value.length} 个退款申请吗？`,
      "批量通过",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }
    );

    selectedRefunds.value.forEach((item: any) => {
      if (item.status === "pending") {
        item.status = "approved";
        item.processTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
        item.processor = "当前用户";
      }
    });

    ElMessage.success(`已批量通过 ${selectedRefunds.value.length} 个退款申请`);
    selectedRefunds.value = [];
  } catch {
    // 用户取消
  }
};

// 批量拒绝
const handleBatchReject = async () => {
  try {
    const { value } = await ElMessageBox.prompt(
      `请输入批量拒绝的原因：`,
      "批量拒绝",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "textarea",
        inputPlaceholder: "请输入拒绝原因"
      }
    );

    selectedRefunds.value.forEach((item: any) => {
      if (item.status === "pending") {
        item.status = "rejected";
        item.processTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
        item.processor = "当前用户";
        item.processRemark = value;
      }
    });

    ElMessage.success(`已批量拒绝 ${selectedRefunds.value.length} 个退款申请`);
    selectedRefunds.value = [];
  } catch {
    // 用户取消
  }
};

// 导出数据
const handleExport = () => {
  ElMessage.success("导出功能开发中");
};

// 统计分析
const handleStatistics = () => {
  statisticsVisible.value = true;
  nextTick(() => {
    initChart();
  });
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  const chart = echarts.init(chartRef.value);

  const option = {
    title: {
      text: "退款状态分布",
      left: "center"
    },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)"
    },
    legend: {
      orient: "vertical",
      left: "left"
    },
    series: [
      {
        name: "退款状态",
        type: "pie",
        radius: "50%",
        data: [
          { value: 35, name: "待审核" },
          { value: 28, name: "审核通过" },
          { value: 142, name: "退款成功" },
          { value: 8, name: "审核拒绝" },
          { value: 6, name: "退款失败" }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  };

  chart.setOption(option);
};

// 分页变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  loadRefundList();
};

const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadRefundList();
};

// 加载退款列表
const loadRefundList = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    pagination.total = 156;
  } catch (error) {
    ElMessage.error("加载退款列表失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadRefundList();
});
</script>

<style scoped lang="scss">
.refund-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .action-left,
  .action-right {
    display: flex;
    gap: 12px;
  }
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;

  .user-detail {
    .username {
      font-weight: 500;
      color: #303133;
    }

    .phone {
      font-size: 12px;
      color: #909399;
    }
  }
}

.amount-info {
  .original-amount {
    font-size: 12px;
    color: #909399;
  }

  .refund-amount {
    font-weight: 500;
    color: #f56c6c;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.refund-detail {
  .el-descriptions {
    margin-bottom: 20px;
  }
}

.process-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}

.statistics-content {
  .el-row {
    margin-bottom: 20px;
  }

  .chart-container {
    margin-top: 20px;
  }
}

@media (max-width: 768px) {
  .refund-container {
    padding: 10px;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }

  .user-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
}
</style>
